<template>
  <div class="order-search">
    <SearchInput
      placeholder="订单商品名称"
      v-model="word"
      showBack
      @onSearch="onSearch"
    />
    <OrderList
      v-model="listLoad"
      :finished="finished"
      :orderList="orderList"
      @next="onload"
      @deal="dealOrder"
    />
  </div>
</template>
<script>
export default {
  layout: "notabbar",
  async asyncData({ app, query }) {
    let { word } = query;
    let orderList = [],
      page = 1,
      pagesize = 10,
      finished = true;
    if (word) {
      try {
        const {
          data,
          page: p,
          pagesize: ps,
          total: t
        } = await app.$apiGetOrder({
          word
        });
        orderList = data;
        finished = p * ps >= t;
        page = p + 1;
      } catch (error) {
        console.log(error);
      }
    }
    return { orderList, page, pagesize, finished, word };
  },
  data: () => ({
    word: "",
    listLoad: false,
    finished: true,
    orderList: [],
    page: 1
  }),
  methods: {
    onSearch(val) {
      this.$router.push({ name: "order-search", query: { word: val } });
    },
    onload() {
      const { page, word } = this;
      this.getList({ page, word }, true);
    },
    getList(data, isConcat) {
      const loading = this.$helperLoadding();
      this.listLoad = true;
      this.$apiGetOrder(data)
        .then(res => {
          const { data, page, pagesize, total } = res;
          this.finished = page * pagesize >= total;
          this.page = page + 1;
          if (isConcat) {
            this.orderList = this.orderList.concat(data);
          } else {
            this.orderList = data;
          }
        })
        .finally(() => {
          loading.clear();
          this.listLoad = false;
        });
    },
    // 处理订单
    dealOrder(info) {
      const data = { type: info.type, order_id: info.order.order_id };
      const loading = this.$helperLoadding();
      const word = this.word;
      this.$apiUpdateOrder(data)
        .then(res => {
          if (res.status === 0) {
            this.getList({ word });
          }
        })
        .finally(() => {
          loading.clear();
          info.cb();
        });
    }
  },
  watchQuery: ["word"]
};
</script>
<style lang="scss" scoped>
.order-search {
  padding: 50px 0 15px;
  background-color: #e9e9e9;
  min-height: 100vh;
  box-sizing: border-box;
  ::v-deep .search-input {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 1;
  }
  ::v-deep > .van-list {
    background-color: #e9e9e9;
  }
  ::v-deep .empty {
    height: calc(100vh - 50px);
  }
}
</style>
